
const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')
const stu = require('./students')

const server = http.createServer((req, res) => {
    let urlObj = url.parse(req.url, true)

    // / 主页
    if (req.url === '/') {
        let filePath = path.join(__dirname, './views/index.html')
        fs.readFile(filePath, 'utf8', (err, fileContent) => {
            res.setHeader('Content-Type', 'text/html;charset=utf8')
            if (err) {
                throw err
            }
            // 读取所有学生信息
            stu.findAll((err, allStudents) => {
                if (err) {
                    throw err
                }
                let strContent = ``
                // 对学生进行循环遍历
                allStudents.forEach((item, index) => {
                    strContent += `
                    <tr>
                    <td>${index}</td>
                    <td>${item.name}</td>
                    <td>${item.age}</td>
                    <td>${item.gender}</td>
                    <td>${item.hobbies}</td>
                    <td>
                    <a href="./views/update.html?id=${item.id}">修改</a>
                    <a href="/delete/student?id=${item.id}">删除</a>
                    </td>
                  </tr>
                    `
                })
                // 把index.html 里面的=_=替换成 strContent
                fileContent = fileContent.replace('=_=', strContent)
                res.end(fileContent)
            })

        })
    }
    // 返回 bootstrap.min.css文件
    else if (req.url === '/node_modules/bootstrap/dist/css/bootstrap.min.css') {
        let filePath = path.join(__dirname, './node_modules/bootstrap/dist/css/bootstrap.min.css')
        fs.readFile(filePath, 'utf8', (err, fileContent) => {
            res.setHeader('Content-Type', 'text/css;charset=utf8')
            if (err) {
                throw err
            }
            res.end(fileContent)
        })
    }
    // 返回 index.css文件
    else if (req.url === '/public/css/index.css') {
        let filePath = path.join(__dirname, './public/css/index.css')
        fs.readFile(filePath, 'utf8', (err, fileContent) => {
            res.setHeader('Content-Type', 'text/css;charset=utf8')
            if (err) {
                throw err
            }
            res.end(fileContent)
        })
    } else if (req.url === '/add/student') {
        let filePath = path.join(__dirname, './views/new.html')
        fs.readFile(filePath, 'utf8', (err, fileContent) => {
            res.setHeader('Content-Type', 'text/html;charset=utf8')
            if (err) {
                throw err
            }

            res.end(fileContent)

        })
    } else if (urlObj.pathname === '/addStudent') {
        let student = urlObj.query
        // console.log(student);
        stu.addStudent(JSON.stringify(student), (err) => {
            if (err) {
                throw err
            }
            // 添加成功后，重定向到 /
            res.statusCode = 302
            res.setHeader('Location', '/')
            res.end()
        })
    } else if (urlObj.pathname === '/views/update.html') {
        let filePath = path.join(__dirname, './views/update.html')
        fs.readFile(filePath, 'utf8', (err, fileContent) => {
            res.setHeader('Content-Type', 'text/html;charset=utf8')
            if (err) {
                throw err
            }
            let id = urlObj.query.id
            stu.findStudentById(Number(id),(err,student)=>{
                if(err){
                    throw err
                }
                let formStr = `
                <form class="form-horizontal" action="/updateStudent" method="GET">
                <input type = "hidden" value="${student.id}" name="id">
                <div class="form-group">
                    <label for="studentname" class="col-sm-2 control-label">姓名：</label>
                    <div class="col-sm-10">
                        <input type="text" value=${student.name} name="name" required class="form-control" id="studentname" placeholder="请输入学生姓名">
                    </div>
                </div>
                <div class="form-group">
                    <label for="age" class="col-sm-2 control-label">年龄：</label>
                    <div class="col-sm-10">
                        <input name="age" value=${student.age} type="number" required class="form-control" id="age" placeholder="请输入年龄">
                    </div>
                </div>
                <div class="form-group">
                    <label for="gender" class="col-sm-2 control-label">性别：</label>
                    <div class="col-sm-10">
                        <input type="radio" name="gender"  required class="radio-inline" value="1">男
                        <input type="radio" name="gender"  required class="radio-inline" value="0" >女
                    </div>
                </div>

                <div class="form-group">
                    <label for="hobbies" class="col-sm-2 control-label">爱好：</label>
                    <div class="col-sm-10">
                        <input name="hobbies" value=${student.hobbies} type="text" required class="form-control" id="hobbies" placeholder="请输入爱好" >
                    </div>
                </div>
                <div class="form-group">
                    <label for="classID" class="col-sm-2 control-label">班级：</label>
                    <div class="col-sm-10">
                        <input name="classID" value = ${student.classID} type="text" required class="form-control" id="classID" placeholder="请输入班级" >
                    </div>
                </div>


                
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-success">修改</button>
                    </div>
                </div>
            </form>
                `
                fileContent = fileContent.replace('=_=',formStr);
                res.end(fileContent)
            })
           

        })
    } else if(urlObj.pathname  === '/updateStudent'){
        let student = urlObj.query
        console.log(student);
        stu.updateStudent(JSON.stringify(student),(err)=>{
            if(err){
                throw err
            }
            res.statusCode=302
            res.setHeader('Location','/')
            res.end()
        })
       
    }else if(urlObj.pathname === '/delete/student'){
        let id  = urlObj.query.id
        stu.deleteStudentById(Number(id),(err)=>{
            if(err){
                throw err
            }
            res.statusCode=302
            res.setHeader('Location','/')
            res.end()
        })
    }else if(urlObj.pathname === '/public/js/index.js'){
        let filePath = path.join(__dirname, './public/js/index.js')
        fs.readFile(filePath, 'utf8', (err, fileContent) => {
            res.setHeader('Content-Type', 'application/x-javascript;charset=utf8')
            if (err) {
                throw err
            }
            res.end(fileContent)
        })
    }else if(urlObj.pathname === '/node_modules/echarts/dist/echarts.js'){
        let filePath = path.join(__dirname, './node_modules/echarts/dist/echarts.js')
        fs.readFile(filePath, 'utf8', (err, fileContent) => {
            res.setHeader('Content-Type', 'application/x-javascript;charset=utf8')
            if (err) {
                throw err
            }
            res.end(fileContent)
        }) 
    }
})

server.listen(3003, () => {
    console.log(`server is running... port 3003`);
})